<?php
class Inventory_model extends CI_Model{
	function __construct(){
		parent::__construct();
	}

	public function get_all(){
		$query = $this->db->get('inventory');
		return $query->result();
	}

	public function get_updated($day){

		$this->db->where('inventory_modified_date >= DATE_SUB(NOW(), INTERVAL '.$day.' DAY)');
		$query = $this->db->get('inventory');
		return $query->result();
	}

	public function add($item_id, $inventory_current_stock, $inventory_min_stock){
		$data = array(
				'item_id' => $item_id,
				'inventory_current_stock' => $inventory_current_stock,
				'inventory_min_stock' => $inventory_min_stock
		);
		if ($this->db->insert('inventory', $data))
			return true;
		else
			return false;
	}

	public function update($item_id, $inventory_current_stock, $inventory_min_stock){
		$data = array(
				'inventory_current_stock' => $inventory_current_stock,
				'inventory_min_stock' => $inventory_min_stock
		);
		$this->db->set('inventory_modified_date', 'now()', false);
		$this->db->where('item_id', $item_id);
		if ($this->db->update('inventory', $data))
			return true;
		else
			return false;
	}

	public function reduce_stock($item_id, $amount){
		$this->db->set('inventory_current_stock', 'inventory_current_stock - '. $amount, false);
		$this->db->where('inventory.item_id', $item_id);
		$this->db->where('item_active', 1);
		if ($this->db->update('inventory join item on item.item_id = inventory.item_id')){
			if ($this->db->affected_rows())
				return true;
		}
		return false;
	}

	public function increase_stock($item_id, $amount){
		$this->db->set('inventory_current_stock', 'inventory_current_stock + '. $amount, false);
		$this->db->where('item_id', $item_id);
		if ($this->db->update('inventory'))
			return true;
		else
			return false;
	}

	public function get_inventory_by_item_id($id){
		$query = $this->db->where('item_id', $id)->get('inventory');

		if ($query->num_rows() > 0)
		{
			return $query->row();
		}else
			return null;
	}
	
	public function get_restock_count(){
		$this->db->from('item');
		$this->db->join('inventory', 'inventory.item_id = item.item_id');
		$this->db->where('inventory_min_stock >= inventory_current_stock');
		$this->db->where('item_active', 1);
		return $this->db->count_all_results();
	}
	
}